/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.econsole.business.sys.controller.ResourceController.java 
 * <p>
 * 类产生时间: 2014-5-12 下午 15:46
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package cn.com.oceansoft.business.sys.controller;

import cn.com.oceansoft.business.base.controller.BaseController;
import cn.com.oceansoft.business.base.entity.Pager;
import cn.com.oceansoft.business.base.entity.Query;
import cn.com.oceansoft.business.base.entity.Result;
import cn.com.oceansoft.business.sys.entity.ResourceTree;
import cn.com.oceansoft.business.sys.entity.SysResource;
import cn.com.oceansoft.business.sys.service.ISysResourceService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 系统资源管理控制器
 *
 * @author: chenw
 * @time: 2014-5-12 下午 15:46
 */
@Controller
@RequestMapping("sys/resource")
public class SysResourceController extends BaseController {

    @Resource
    private ISysResourceService resourceService;

    /**
     * 进入系统资源管理首页（列表）
     *
     * @return String
     */
    @RequestMapping(value = "index", method = GET)
    public String gotoResourceIndex(Query query, Model model) {
        query.setOrderField("sort");
        query.setOrderDirection("asc");
        model.addAttribute("query", query);
        model.addAttribute("pager", resourceService.findResourceByCondition(query));
        log("查看系统资源列表");
        return "sys/sys-resource-list";
    }

    /**
     * 列表分页显示
     *
     * @param query 分页查询条件
     * @param model 数据Model
     * @return 页面地址
     */
    @RequestMapping(value = "list", method = POST)
    public String loadPageByCondition(Query query, Model model) {
        Pager pager = resourceService.findResourceByCondition(query);
        model.addAttribute("query", query);
        model.addAttribute("pager", pager);
        log(String.format("查看系统资源第%d页", query.getPageNum()));
        return "sys/sys-resource-list";
    }

    /**
     * 进入系统角色资源绑定界面
     *
     * @return String
     */
    @RequestMapping(value = "tree/{role_id}", method = GET)
    public String viewRoleResourceBind(@PathVariable("role_id") int roleId, Model model) {
        //加载指定角色权限信息，此列表返回的值为全部资源与当前角色绑定资源合集。即当前角色绑定的资源，则返回的列表FLAG字段为checked,返回为空
        List<SysResource> list = resourceService.findResourcesTreeByRoleId(roleId);
        Map<Integer, ResourceTree> treeMap = new LinkedHashMap<Integer, ResourceTree>();
        for (SysResource res : list) {
            if (treeMap.containsKey(res.getParentId())) {
                if (res.getParentId() != 0) //是叶子节点
                    treeMap.get(res.getParentId()).getLeaf().add(res);
            } else {
                if (res.getParentId() == 0) {
                    ResourceTree group = new ResourceTree();
                    group.setText(res.getName());
                    group.setFlag(res.getFlag());
                    group.setRemark(res.getRemark());
                    group.setId(res.getId());
                    group.setLeaf(new ArrayList<SysResource>());
                    treeMap.put(res.getId(), group);
                }
            }
        }
        //需要隐藏的没有叶子节点的节点
        List<Integer> needRemove = new ArrayList<Integer>();
        for (Iterator<Integer> i = treeMap.keySet().iterator(); i.hasNext();) {
        	Integer treeNode = i.next();
        	ResourceTree tree = treeMap.get(treeNode);
        	if(tree.getLeaf().size()==0){
        		needRemove.add(treeNode);
        	}
        }
        //将需要隐藏的节点移除
        for(Integer ri:needRemove){
        	treeMap.remove(ri);
        }
        model.addAttribute("roleId", roleId);
        model.addAttribute("tree", CollectionUtils.arrayToList(treeMap.values().toArray()));
        return "sys/role-res-bind";
    }

    /**
     * 新增角色资源关联信息
     *
     * @param roleId 角色ID
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "bind/{role_id}", method = POST)
    public Result bindRoleResources(@PathVariable("role_id") int roleId, @RequestParam("ids") int[] ids) {
        resourceService.updateRoleResourceBatch(roleId, ids);
        return new Result();
    }

    /**
     * 进入资源编辑页面
     *
     * @param resourceId 资源ID
     * @param model      页面数据MODEL
     * @return 页面路径
     */
    @RequestMapping(value = "edit/{resource-id}", method = GET)
    public String gotoResourceEdit(@PathVariable("resource-id") int resourceId, Model model) {
        SysResource resource = resourceService.findResourceIdById(resourceId);
        model.addAttribute("resource", resource);
        return "sys/sys-resource-edit";
    }

    /**
     * 资源编辑表单提交
     *
     * @param resource 资源ID
     * @return 处理结果
     */
    @ResponseBody
    @RequestMapping(value = "edit", method = POST)
    public Result editResource(SysResource resource) {
        log(String.format("更新系统资源[%s]信息", resource.getName()));
        return resourceService.updateResource(resource);
    }

    @ResponseBody
    @RequestMapping(value = "del/{id}", method = RequestMethod.DELETE)
    public Result del(@PathVariable("id") int id) {
        Result rt=null;
        try {
            rt=resourceService.remove(id);
        }catch (Exception e){
            e.printStackTrace();
            rt=new Result(Result.FAILURE,"删除异常");
        }

        log(String.format("删除编号为%d系统资源%s", id, rt.isSucc() ? "成功" : "失败"));
        return rt;
    }

    /**
     * 转添加页面
     * @return
     */
    @RequestMapping(value = "toadd", method = RequestMethod.GET)
    public String toAdd(Model model) {
        List<SysResource> list=resourceService.findResourcesByParentId(0);
        model.addAttribute("list",list);
        return "sys/sys-resource-new";
    }

    /**
     * 添加
     * @param sysResource
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public Result add(SysResource sysResource, HttpServletRequest request) {
        String method=request.getParameter("sysResource.method");
        sysResource.setMethod(method);
        return resourceService.add(sysResource);
    }
}
